package com.huluobo.base.mvvm

import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.huluobo.base.net.Res
import kotlinx.coroutines.launch
import java.lang.RuntimeException

/**
 *  Created by LC on 2024/11/27.
 */
open class BaseViewModel : ViewModel() {
    val onFailed by lazy { MutableLiveData<Throwable>() }

    fun <T> executeNetwork(
        s: suspend () -> Res<T>,
        success: (T) -> Unit,
        failed: (Throwable) -> Unit = onFailed::postValue,
        okCode: Int = 200
    ) {
        viewModelScope.launch {
            try {
                val res = s.invoke()
                Log.i("TagA", "res:$res")
                if (res.code == okCode) {
                    success(res.data)
                } else {
                    failed(RuntimeException(res.message))
                }
            } catch (e: Exception) {
                failed(e)
            }
        }
    }

    fun <T> executeDb(
        s: suspend () -> T,
        success: (T) -> Unit,
        failed: (Throwable) -> Unit = onFailed::postValue
    ) {
        viewModelScope.launch {
            try {
                success(s.invoke())
            } catch (e: Exception) {
                failed(e)
            }
        }
    }

}